package model

import (
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

/**
 * @Author: way lee
 * @Date: 2024/9/10 10:10
 * @Desc:
 */

type ComponentInfo struct {
	ID             int64          `db:"id"`
	ComponentName  string         `db:"component_name"`
	Version        sql.NullString `db:"version"`
	NodeHost       string         `db:"node_host"`
	ComponentRole  string         `db:"component_role"`
	HomePath       sql.NullString `db:"home_path"`
	DataStorageDir sql.NullString `db:"data_storage_dir"`
	Port           sql.NullString `db:"port"`
	Status         bool           `db:"status"`
	AdditionalInfo sql.NullString `db:"additional_info"`
	CreatedAt      sql.NullString `db:"created_at"`
	UpdatedAt      sql.NullString `db:"updated_at"`
}

type ComponentInfoModel struct {
	Conn      sqlx.SqlConn
	TableName string
}

func NewComponentInfoModel(conn sqlx.SqlConn, tableName string) *ComponentInfoModel {
	return &ComponentInfoModel{
		Conn:      conn,
		TableName: tableName}
}

func (m *ComponentInfoModel) FindByComponentNameAndRole(componentName, componentRole string) ([]*ComponentInfo, error) {
	query := fmt.Sprintf(`SELECT id, component_name, version, node_host, component_role, home_path, data_storage_dir, port, status, additional_info, created_at, updated_at 
			  FROM %s WHERE component_name = ? AND component_role = ?`, m.TableName)
	var components []*ComponentInfo
	err := m.Conn.QueryRows(&components, query, componentName, componentRole)
	if err != nil {
		return nil, fmt.Errorf("error querying component info: %w", err)
	}
	return components, nil
}
